import { createApp } from 'vue'
import './app.scss'
import { createPinia } from 'pinia'
//import { Tabs, TabPane } from '@nutui/nutui-taro';


import { useGlobalStore } from './stores';
import { useUserStore } from './stores/user';
import { getEnv, getEnvs, getStorageSync, login, setStorage } from './utils/framework';
import { AccessTokenInfo } from './types/AccessTokenInfo';
import { loginApi } from './api/Login';

const App = createApp({
  async onLaunch(options) {
    const globalStore = useGlobalStore()
    const userStore = useUserStore()
    const env = getEnv()
    const envs = getEnvs()
    if(env == envs.WEAPP) { //微信小程序
      globalStore.isWX = true
      globalStore.client = 'wx'
      
      globalStore.provider = 'weixin'
    }else {
      globalStore.isAli = true
      globalStore.client = 'ali'
      globalStore.provider = 'alipay'
    }
    
    const tokenInfo = getStorageSync<AccessTokenInfo>(process.env.B_TOKEN_KEY as string)
    let loginStatus = false
    if(tokenInfo) {
     
      //if((tokenInfo.expireIn - (Date.now() / 1000)) > (10 * 60)) {//token过期时间已经少于五分钟了则视为过期
        loginStatus = true
        globalStore.accessToken = tokenInfo.token
      //}
    }
    return


    // if(globalStore.isWX && loginStatus) {
    //   const res = await checkSession()
    //   console.log(res)
    //   if(!res) { //需要重新登录
    //     loginStatus = false
    //   }
    // }

    let params:any = {

    }

    if(globalStore.isWX) {
      params.provider = 'weixin'
    }else {
      params.scopes = ['auth_base', 'auth_user']
    }


    const code = await login(globalStore.client, params)


    if(code !== null) {
      loginApi(code).then(res => {
        userStore.nickname = res.data.user.nickname
        userStore.avatar = res.data.user.avatar
        userStore.isAuthPhone = res.data.user.phoneAuth
        userStore.payscore = res.data.user.payscore

        
        globalStore.accessToken = res.data.accessToken
        setStorage<AccessTokenInfo>(process.env.B_TOKEN_KEY as string, {token : res.data.accessToken, expireIn : res.data.expire})
        globalStore.loginStatus = true

        
      })
    }


  },
  onShow(options) {

  }
})

//App.use(Tabs).use(TabPane);


App.use(createPinia())

export default App
